<template>
  <view class="viewport">
    <scroll-view enable-back-to-top scroll-y class="scroll">
      <uni-section :title="ID ? '编辑' : '新增'" type="line">
        <view class="example">
          <uni-forms ref="baseForm" :modelValue="form">
            <uni-forms-item label="创建人">
              <uni-easyinput v-model="form.UserName" disabled="true" />
            </uni-forms-item>
            <uni-forms-item label="任务名称">
              <uni-easyinput v-model="form.JobName" placeholder="请输入任务名称" />
            </uni-forms-item>
            <uni-forms-item label="记账类型">
              <uni-data-select
                v-model="form.AccountType"
                :localdata="accountTypedata"
                @change="changeAccountType"
              ></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="商品类型" v-if="form.AccountType !== '转账'">
              <uni-data-select v-model="form.GoodsType" :localdata="goodTypedata"></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="商品" v-if="form.AccountType !== '转账'">
              <uni-easyinput v-model="form.Goods" placeholder="请输入商品" />
            </uni-forms-item>
            <uni-forms-item label="执行时间">
              <uni-datetime-picker type="datetime" v-model="form.TriggerTime" />
            </uni-forms-item>
            <uni-forms-item label="周期">
              <uni-data-select
                v-model="form.RepeateType"
                :localdata="repeateTypedata"
              ></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="账户来源" v-if="form.AccountType == '转账'">
              <uni-data-select
                v-model="form.AccountFrom"
                :localdata="accountFromdata"
              ></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="账户目标">
              <uni-data-select
                v-model="form.AccountTo"
                :localdata="accountTodata"
              ></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="金额">
              <uni-easyinput v-model="form.Amount" placeholder="请输入金额" />
            </uni-forms-item>
            <uni-forms-item v-if="form.AccountType == '支出'" label="不计入预算" label-width="600">
              <uni-data-checkbox v-model="form.IsNotYuSuan" :localdata="checkdata" mode="default" />
            </uni-forms-item>
            <uni-forms-item v-if="form.AccountType == '支出'" label="是否刚需" label-width="600">
              <uni-data-checkbox v-model="form.IsRequire" :localdata="checkdata" mode="default" />
            </uni-forms-item>
            <uni-forms-item label="是否启用" label-width="600">
              <uni-data-checkbox v-model="form.IsEnable" :localdata="checkdata" mode="default" />
            </uni-forms-item>
            <uni-forms-item label="备注">
              <uni-easyinput v-model="form.Remark" placeholder="可输入备注" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </uni-section>
      <button class="button btn" @click="ok">确认</button>
      <button class="button btn" @click="OnAlertDialog" v-if="ID">删除</button>
      <button class="button btn" @click="back">取消</button>
    </scroll-view>
  </view>
  <!-- 提示确认是否删除 弹窗 -->
  <uni-popup ref="alertDialog" type="dialog">
    <uni-popup-dialog
      type="warn"
      cancelText="取消"
      confirmText="确定"
      title="通知"
      content="确定要删除么？"
      @confirm="del"
      @close="cancel"
    ></uni-popup-dialog>
  </uni-popup>
</template>
<script setup lang="ts">
import { GetUserAccountAPI } from '@/services/detail'
import {
  AddNoteAccountJobAPI,
  DelNoteAccountJobAPI,
  GetGoodTypesAPI,
  GetOneNoteAccountJobAPI,
  NoteAccountJobAPI,
  UpdateNoteAccountJobAPI,
} from '@/services/job'
import { useMemberStore } from '@/stores'
import type { GoodType } from '@/types/detail'
import type { GetNoteAccountJobResponse, selectdata } from '@/types/job'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取会员信息
const memberStore = useMemberStore()
const form = ref<GetNoteAccountJobResponse>({
  ID: 0,
  JobName: '',
  TriggerTime: new Date(),
  RepeateType: '',
  Amount: 0,
  AccountType: '',
  Remark: '',
  AccountFrom: '',
  AccountTo: '',
  Goods: '',
  GoodsType: '',
  UserName: '',
  IsNotYuSuan: false,
  IsEnable: true,
  IsRequire: true,
  UserGroup: '',
})
const userdata = ref([
  { value: '哥哥', text: '哥哥' },
  { value: '遥遥', text: '遥遥' },
])
const accountTypedata = ref([
  { value: '收入', text: '收入' },
  { value: '支出', text: '支出' },
  { value: '转账', text: '转账' },
])
const checkdata = [
  { value: true, text: '是' },
  { value: false, text: '否' },
]
const repeateTypedata = ref([
  { value: '日', text: '日' },
  { value: '周', text: '周' },
  { value: '月', text: '月' },
  { value: '年', text: '年' },
])
//提示框
const alertDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const ID = ref<number>()
const goodTypedata = ref<selectdata[]>()
const accountFromdata = ref<selectdata[]>()
const accountTodata = ref<selectdata[]>()

//============================以下函数========================
//加载初始化
onLoad(async (option) => {
  if (memberStore.profile) {
    console.log('ID' + option?.ID)
    ID.value = option?.ID
    form.value.UserName = memberStore.profile.UserName
    form.value.UserGroup = memberStore.profile.UserGroup
    await InitUserAccount()
    await reFresh()
    await InitGoodTypes(form.value.AccountType)
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
})
onShow(async () => {
  reFresh()
})
//刷新事件
const reFresh = async () => {
  if (ID.value) {
    if (memberStore.profile) {
      const res = await GetOneNoteAccountJobAPI({
        Auth: memberStore.profile.Token,
        ID: ID.value,
      })
      form.value = res.result
    } else {
      uni.showToast({ icon: 'none', title: '请先登录' })
      setTimeout(() => {
        // 页面跳转
        uni.switchTab({ url: '/pages/my/my' })
      }, 500)
    }
  }
}
//初始化账户列表
const InitUserAccount = async () => {
  if (memberStore.profile) {
    const res = await GetUserAccountAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    let data = res.result.map((item) => ({ value: item.AccountNo, text: item.Display }))
    accountFromdata.value = data
    accountTodata.value = data
  }
}
//初始化商品类别
const InitGoodTypes = async (e: string) => {
  const res = await GetGoodTypesAPI({
    inout: e,
    UserGroup: memberStore.profile!.UserGroup,
  })
  goodTypedata.value = res.result
}

//返回
const back = () => {
  uni.navigateTo({ url: '/pages/Job/Job' })
}
//确认
const ok = async () => {
  if (ID.value) {
    const res = await UpdateNoteAccountJobAPI(form.value)
  } else {
    const res = await AddNoteAccountJobAPI(form.value)
  }

  // 成功提示
  uni.showToast({ icon: 'success', title: '保存成功' })
  setTimeout(() => {
    // 页面跳转
    uni.navigateTo({ url: '/pages/Job/Job' })
  }, 500)
}
//删除时，打开确认框
const OnAlertDialog = async () => {
  alertDialog.value?.open()
}
//取消
const cancel = async () => {
  alertDialog.value?.close()
}
//确认删除
const del = async () => {
  const res = await DelNoteAccountJobAPI({
    Auth: memberStore!.profile!.Token,
    ID: ID.value!,
  })
  // 成功提示
  uni.showToast({ icon: 'success', title: '保存成功' })
  setTimeout(() => {
    // 页面跳转
    uni.navigateTo({ url: '/pages/Job/Job' })
  }, 500)
}

//下拉选择事件
const changeAccountType = async (e: any) => {
  await InitGoodTypes(e)
}
</script>
<style lang="scss">
@import './styles/JobDetail.scss';
</style>
